package com.information.controller;

import com.information.service.RedisService;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/redis")
public class RedisController {

    private final RedisService redisService;

    public RedisController(RedisService redisService) {
        this.redisService = redisService;
    }

    /**
     * 测试RDS是否连接成功
     * @return String
     */
    @GetMapping("/test")
    public String testConnection() {
        try {
            redisService.setString("test", "InforSuiteRDS 连接成功！");
            String result = redisService.getString("test");
            return "连接成功: " + result;
        } catch (Exception e) {
            return "连接失败: " + e.getMessage();
        }
    }

    /**
     * 向缓存中添加键值对
     * @param key
     * @param value
     * @return String
     */
    @PostMapping("/set/{key}")
    public String setValue(@PathVariable String key, @RequestBody String value) {
        redisService.setString(key, value);
        return "设置成功";
    }

    /**
     * 从缓存中获取键
     * @param key
     * @return String
     */
    @GetMapping("/get/{key}")
    public String getValue(@PathVariable String key) {
        return redisService.getString(key);
    }

    /**
     * 获取缓存信息
     * @return String
     */
    @GetMapping("/info")
    public String getRedisInfo() {
        try {
            return redisService.getConnectionInfo();
        } catch (Exception e) {
            return "获取Redis信息失败: " + e.getMessage();
        }
    }

    /**
     * 获取连接状态
     * @return Map<String, Object>
     */
    @GetMapping("/status")
    public Map<String, Object> getConnectionStatus() {
        Map<String, Object> status = new HashMap<>();
        try {
            // 测试基本连接
            redisService.setString("health_check", "OK");
            String result = redisService.getString("health_check");

            status.put("connected", true);
            status.put("ping", redisService.ping());
            status.put("test_result", result);
            status.put("timestamp", new Date());
        } catch (Exception e) {
            status.put("connected", false);
            status.put("error", e.getMessage());
            status.put("timestamp", new Date());
        }
        return status;
    }
}